<?php

namespace app\store\model\appointment;

use app\common\model\AppointmentOrder as AppointmentOrderModel;
use app\store\model\Goods as GoodsModel;
use app\common\model\BaseModel;
use app\common\model\AppointmentService as ServiceModel;
use app\common\model\UploadFile as UploadFileModel;
use think\Db;
use  \app\common\model\server\User as UserModel;

/**
 * 预约订单模型
 * Class BalanceLog
 * @package app\store\model\user
 */
class Order extends BaseModel
{
    protected $name = 'appointment_order';

    protected $append = ['is_offline_text'];
    /**
     * 获取余额变动明细列表
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($dataType, $query = [])
    {

        // 检索查询条件
        !empty($query) && $this->setWhere($query);

        // 获取数据列表
        $list = $this->with('order_info,time,type')
            ->alias('offline')
            ->field('offline.*,offline.order_id,offline.is_self,offline.is_offline,offline.user_name,offline.user_phone,offline.create_time,offline.num,
            offline.address,offline.appointment_date,offline.status,offline.offline_pay_status,
            offline.service_name,order.total_price,type.name type_name, offline.id,offline.offline_name,offline.time_id')
            ->join('order', 'offline.user_order_id = order.order_id', 'left')
//            ->join('appointment_time time', 'time.time_id = offline.time_id', 'left')
            ->join('appointment_type type', 'type.type_id = offline.type_id', 'left')
            ->where('offline.is_delete', 0)
            ->order(['offline.create_time' => 'desc'])
            ->paginate(10, false, [
                'query' => \request()->request()
            ])->each(function ($item, $key) {
                $item['user_name'] = !empty($item['user_name']) ? $item['user_name'] : '';
                $item['user_phone'] = !empty($item['user_phone']) ? $item['user_phone'] : '';
                $item['address'] = !empty($item['address']) ? $item['address'] : '';
                $item['total_price'] = !empty($item['total_price']) ? $item['total_price'] : 0;
                if($item['is_offline'] == 1){
                    $item['offline_pay_status'] = $item['offline_pay_status'] == 1 ? '已支付' : '未支付';
                }else{
                    $item['offline_pay_status'] = '已支付';
                }

                $time_arr = explode(',',$item['time_id']);

                $item['time_name_arr'] = Db::name('appointment_time')->where(['time_id'=>['in',$time_arr]])->column('name');

                $uploadFile = new UploadFileModel;

                $images = Db::name('appointment_image')->where(['order_id' => $item['id']])->field('id,image_id')->select();

                $images = collection($images)->toArray();

                $ping_image = empty($item['ping_img'])  ? [] : explode(',',$item['ping_img']);

                foreach ($ping_image as $kk => $vv ){
                    $image = $uploadFile->detail($vv);
                    $ping_image[$kk] = $image['file_path'];
                }
                foreach ($images as &$val) {
                    if ($val['image_id']) {
                        $image = $uploadFile->detail($val['image_id']);
                        $val['image'] = $image['file_path'];
                    }
                }
                $item['images'] = $images;
                $item['ping_img'] = empty($ping_image) ? [] : $ping_image;
                $order = Db::name('order')->where(['order_id' => $item['user_order_id']])->find();
                if($order['order_status'] == 20){
                    $item['iscancel'] = 1;
                }else{
                    $item['iscancel'] = 0;
                }
            });

        return $list;


        // 设置查询条件
        !empty($query) && $this->setQueryWhere($query);

        // 获取列表数据
        $list = $this->alias('order')
            ->field('order.id,order.order_id,user_name,service_name,appointment_date,order.status,user_order_id,order.time_id,
           type.name type_name,order.create_time,order.offline_name')
//            ->join('appointment_time time', 'order.time_id = time.time_id', 'left')
            ->join('appointment_type type', 'order.type_id = type.type_id', 'left')
            ->order(['order.create_time desc'])
            ->where([
                'order.is_offline' => 0,
                'order.is_delete' => 0,
            ])
            ->paginate(15, false, [
                'query' => \request()->request()
            ])->each(function ($item, $key) {
                $item['date_name'] = date("Y-m-d", $item['appointment_date']);

                switch ($item['status']) {
                    case 1:
                        $item['status_name'] = '未服务';
                        break;
                    case 2:
                        $item['status_name'] = '已服务';
                        break;
                    case 3:
                        $item['status_name'] = '取消服务';
                        break;
                }

                $item['user_order_name'] = '/-/-/';
                if ($item['user_order_id'] > 0) {
                    $user_order = Db("order")->where("order_id", $item['user_order_id'])->field('order_no,total_price')->find();
                    $item['user_order_name'] = $user_order['order_no'] . '<br/>' . $user_order['total_price'];
                }

                $time_id = explode(',',$item['time_id']);
                $time_list = Db::name('appointment_time')->where(['time_id'=>['in',$time_id]])->column('name');
                $str = '';
                foreach ($time_list as $k => $val){
                    if($k == 0){
                        $str .= $val;
                    }else{
                        $str .= '<br>'.$val;
                    }
                }
                $item['time_name'] = $str;

                $uploadFile = new UploadFileModel;
                $images = Db::name('appointment_image')->where(['order_id' => $item['id']])->field('id,image_id')->select();
                $images = collection($images)->toArray();
                foreach ($images as &$val) {
                    if ($val['image_id']) {
                        $image = $uploadFile->detail($val['image_id']);
                        $val['image'] = $image['file_path'];
                    }
                }

                $item['images'] = $images;
            });
        return $list;
    }

    /*
     * 订单详情当前订单预约订单
     */

    public function orderOrderList($user_order_id)
    {

        // 获取列表数据
        $list = $this->alias('order')
            ->field('order.id,order.order_id,user_name,service_name,appointment_date,order.status,user_order_id,
            time.name time_name,type.name type_name,order.create_time,order.offline_name,order.is_offline')
            ->join('appointment_time time', 'order.time_id = time.time_id', 'left')
            ->join('appointment_type type', 'order.type_id = type.type_id', 'left')
            ->order(['order.create_time desc'])
            ->where([
                'order.is_offline' => 0,
                'order.is_delete' => 0,
                'order.user_order_id'=>$user_order_id
            ])
            ->select()->each(function ($item, $key) {
                $item['date_name'] = date("Y-m-d", $item['appointment_date']);

                switch ($item['status']) {
                    case 1:
                        $item['status_name'] = '未服务';
                        break;
                    case 2:
                        $item['status_name'] = '已服务';
                        break;
                    case 3:
                        $item['status_name'] = '取消服务';
                        break;
                    case 4:
                        $item['status_name'] = '取消订单';
                        break;
                }

                $item['user_order_name'] = '/-/-/';
                if ($item['user_order_id'] > 0) {
                    $user_order = Db("order")->where("order_id", $item['user_order_id'])->field('order_no,total_price')->find();
                    $item['user_order_name'] = $user_order['order_no'] . '<br/>' . $user_order['total_price'];
                }

                $uploadFile = new UploadFileModel;
                $images = Db::name('appointment_image')->where(['order_id' => $item['id']])->field('id,image_id')->select();
                $images = collection($images)->toArray();
                foreach ($images as &$val) {
                    if ($val['image_id']) {
                        $image = $uploadFile->detail($val['image_id']);
                        $val['image'] = $image['file_path'];
                    }
                }

                $item['images'] = $images;
            });
        return $list;

    }

    public function getStatusTextAttr($value, $data)
    {
        $status = [1 => '未服务', 2 => '已服务', 3 => '取消订单',4=>'取消服务'];
        return $status[$data['status']];
    }

    public function getIsSelfAttr($value)
    {
        $status = [0 => '否', 1 => '是'];
        return $status[$value];
    }

    public function getIsOfflineTextAttr($value,$data)
    {
        $status = [0 => '线上订单', 1 => '线下订单'];
        return $status[$data['is_offline']];
    }

    public function getAppointmentDateTextAttr($value, $data)
    {

        return $data['appointment_date'] > 0 ? date("Y-m-d ", $data['appointment_date']) : '';
    }

    /**
     * 关联订单表
     * @return \think\model\relation\HasOne
     */
    public function orderInfo()
    {
        $module = self::getCalledModule() ?: 'common';
        return $this->hasOne("app\\{$module}\\model\\Order", 'order_id', 'user_order_id');
    }

    /**
     * 关联订单表
     * @return \think\model\relation\HasOne
     */
    public function time()
    {
        $module = self::getCalledModule() ?: 'common';
        return $this->hasOne("app\\{$module}\\model\\appointment\\Time", 'time_id', 'time_id');
    }

    /**
     * 关联订单表
     * @return \think\model\relation\HasOne
     */
    public function type()
    {
        $module = self::getCalledModule() ?: 'common';
        return $this->hasOne("app\\{$module}\\model\\appointment\\Type", 'type_id', 'type_id');
    }

    /**
     * 设置查询条件
     * @param $query
     */
    private function setWhere($query)
    {
        // 设置默认的检索数据
        $params = $this->setQueryDefaultValue($query, [
            'search' => '',
            'offline.service_id' => -1,
            'offline.status' => 0,
            'start_time' => '',
            'end_time' => '',
        ]);
        // 使用状态
        isset($params['status']) && $params['status'] > 0 && $this->where('offline.status', '=', $params['status']);
        if(isset($params['status']) && $params['status'] == -2){
            $this->where('offline.service_id', '=', 0);
            $this->where('offline.status', '<>', 3);
        }
        if(isset($params['status']) && $params['status'] == -3){
            $this->where('offline.service_id', '>', 0);
        }

        // 用户查询
        if (!empty($params['search'])) {
//            $users = Db("user_address")->where('name|phone', 'like', '%' . $params['search'] . '%')->column('user_id');
            $this->where('offline.user_name|offline.user_phone|offline.order_id', 'like', '%'.$params['search'].'%');
        }

        // 服务人员id
        isset($params['service_id']) && $params['service_id'] > 0 && $this->where('offline.service_id', '=', $params['service_id']);

        // 起始时间
        !empty($params['start_time']) && $this->where('offline.appointment_date', '>=', strtotime($params['start_time']));
        // 截止时间
        !empty($params['end_time']) && $this->where('offline.appointment_date', '<=', strtotime($params['end_time']));
    }
    /**
     * 设置查询条件
     * @param $query
     */
    private function setQueryWhere($query)
    {
        // 设置默认的检索数据
        $params = $this->setQueryDefaultValue($query, [
            'search' => '',
            'order.service_id' => -1,
            'order.status' => 0,
            'start_time' => '',
            'end_time' => '',
        ]);
        // 使用状态
        isset($params['status']) && $params['status'] > 0 && $this->where('order.status', '=', $params['status']);

        // 用户查询
        if (!empty($params['search'])) {
            $users = Db("user_address")->where('name|phone', 'like', '%' . $params['search'] . '%')->column('user_id');
            $this->where('user_id', 'in', $users);
        }

        // 服务人员id
        isset($params['service_id']) && $params['service_id'] > 0 && $this->where('order.service_id', '=', $params['service_id']);

        // 起始时间
        !empty($params['start_time']) && $this->where('order.appointment_date', '>=', strtotime($params['start_time']));
        // 截止时间
        !empty($params['end_time']) && $this->where('order.appointment_date', '<=', strtotime($params['end_time']));
    }

    /**
     * 编辑商品
     * @param $data
     * @return bool|mixed
     */
    public function edit($data)
    {
        if (empty($data['appointment_date'])) return false;

        $data['appointment_date'] = isset($data['appointment_date']) ? strtotime($data['appointment_date']) : '';
        if ($data['id'] > 0) {
            $price = Db("goods_sku")->where([
                'goods_sku_id' => $data['user_goods_sku'],
            ])->value('goods_price');

            $ServiceModel = new ServiceModel();
            $ServiceModel->add_service($data['id'], $data['service_id'], $price, $data['use_time'], $data['num']);
            unset($data['use_time']);
        }
        $data['time_id']  = implode(',',$data['time_id']);
        if($data['status'] == 2){
            //服务完成，用户自动确认
            $OrderModel = new AppointmentOrderModel();

            $detail = $OrderModel::detail($data['id']);

            $OrderModel->updateServerState($data['id'], 4);
            if ($detail['is_offline'] > 0) {
                $OrderModel->where('id', $data['id'])->update(['offline_pay_status' => 1]);
            }
            $serviceModel = new ServiceModel;
            $serviceModel->confirm_finish($data['id']);

        }
        $res = $this->where('order_id', $data['order_id'])->update($data);
        if($res === false){
            return $res;
        }
        return true;
    }

    /**
     * 添加预约
     * @param $data
     * @return bool|mixed
     */
    public function add($data = [])
    {
        if (!isset($data['user_id'])) {
            $this->error = '请选择用户信息';
            return false;
        }

        if (empty($data['type_id'])) {
            $this->error = '预约类型未选择';
            return false;
        }

        $userName = Db("user_address")->where("user_id", $data['user_id'])
            ->where('wxapp_id', self::$wxapp_id)->value('name');
        if (empty($userName)) {
            $this->error = '用户信息未找到';
            return false;
        }

        if (empty($data['appointment_date'])) {
            $this->error = '预约日期未选择';
            return false;
        }

        $data['appointment_date'] = strtotime($data['appointment_date']);

        if (empty($data['time_id'])) {
            $this->error = '时间点未选择';
            return false;
        }
        $data['time_id'] = implode(',',$data['time_id']);
        if (empty($data['service_id'])) {
            $this->error = '服务人员未选择';
            return false;
        }

        if (empty($data['user_order_id'])) {
            $this->error = '客户的订单未选择';
            return false;
        }

        if (empty($data['user_goods_sku'])) {
            $this->error = '订单商品规格未选择';
            return false;
        }
        $user_goods_id = Db::name('goods_sku')->where(['goods_sku_id' => $data['user_goods_sku']])->value('goods_id');
        if (!empty($user_goods_id)) {
            $data['user_goods_id'] = $user_goods_id;
        }
        if (empty($data['user_goods_id'])) {
            $this->error = '订单商品未选择';
            return false;
        }

        $sku_count = Db("order_goods")
            ->where('order_id', $data['user_order_id'])
            ->where('goods_id', $data['user_goods_id'])
            ->where('goods_sku_id', $data['user_goods_sku'])
            ->field('goods_sku_id,goods_sku_ids,total_num,create_time')
            ->find();
        $where = [
            'user_goods_id' => $data['user_goods_id'],
            'user_goods_sku' => $data['user_goods_sku'],
            'user_order_id' => $data['user_order_id'],
            'user_id' => $data['user_id'],
            'is_delete' => 0,
        ];
        $count = Db("appointment_order")
            ->where($where)
            ->where('status', 'in', [1, 2])
            ->count();

        $goods = GoodsModel::detail($data['user_goods_id']);
        switch ($goods['goods_type']) {
            case 0:
                if ($count >= $sku_count['total_num']) {
                    $this->error = '商品预约已用完';
                    return false;
                }
                break;
            case 1:
                if ($goods['goods_expire'] > 60) {
                    $this->error = '有效期配置有误';
                    return false;
                }

                $expire_time = $goods['goods_expire'] * 3600 * 24 * 12;
//                log_print($expire_time, $goods['goods_expire'], $sku_count['create_time']);
                if (time() - $expire_time > $sku_count['create_time']) {
                    $this->error = '服务卡已过期';
                    return false;
                }

                if ($count >= $goods['goods_count']) {
                    $this->error = '商品预约已用完';
                    return false;
                }
                break;
            case 2:
                $month1 = strtotime(date("Y-m-01", time()));
                $month2 = strtotime(date("Y-m-01", strtotime('+1 months')));

                $where1 = "appointment_date >=" . $month1 . " and appointment_date <=" . $month2;
                $count = $this->where($where)
                    ->where($where1)
                    ->where('status', 'in', [1, 2])->count();

                if ($count >= $goods['goods_count_month']) {
                    $this->error = '商品预约已用完';
                    return false;
                }

                $month = date("m", $sku_count['create_time']);
                $cur_month = date("m", time());
                if ($cur_month < $month) $cur_month = $cur_month + 12;
//                log_print($cur_month, $month, $goods['goods_month']);
                if ($cur_month - $month > $goods['goods_month']) {
                    $this->error = '服务卡已过期';
                    return false;
                }
                break;
            case 3:
                break;
        }

        $serverName = Db("server_user")->where("user_id", $data['service_id'])->value('real_name');
        if (empty($serverName)) {
            $this->error = '服务人员信息未找到';
            return false;
        }

        $data['user_name'] = $userName;
        $data['service_name'] = $serverName;
        $data['wxapp_id'] = self::$wxapp_id;
        $data['create_time'] = time();
        $use_time = $data['use_time'];
        unset($data['use_time']);
        $id = $this->insertGetId($data);
        if ($id > 0) {
            $price = Db("goods_sku")->where([
                'goods_sku_id' => $data['user_goods_sku'],
                'goods_id' => $data['user_goods_id'],
            ])->value('goods_price');

            $ServiceModel = new ServiceModel();
            $ServiceModel->add_service($id, $data['service_id'], $price, $use_time);
        }

        return $id > 0 ? true : false;
    }

    /**
     * 获取可预约人员
     * 如果是编辑状态，则把此订单的服务人员排除
     * @param array $params
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getServerMan($params = [])
    {
        $type_id = $params['type_id'];  //预约类型
        $date = $params['date_id'];  //预约日期
        $time_id = $params['time_id'];  //预约时间

        $order_id = isset($params['order_id']) ? $params['order_id'] : 0;
        $where = [
            'is_delete' => 0,
        ];

        $time_id = explode(',',$time_id);

        $date_time = strtotime($date);

        $sub_arr =[];
        $ar = [];
        foreach ($time_id as $val){
            $ids = $this->where("appointment_date", $date_time)
                ->where('find_in_set(:time_id,time_id)',['time_id'=>$val])
                ->where("status", 'in', [1, 2])
                ->where($where)
                ->column('service_id');

            $sub_arr = array_merge($sub_arr, $ids);
        }
        $sub_arr = array_unique($sub_arr);
        $ar = array_merge($ar, $sub_arr);

        if ($order_id > 0) {
            $service_id = $this->where('id', $order_id)->value('service_id');
            $ar = array_diff($ar, [$service_id]);
        }

        return UserModel::allServer($type_id, $ar);
    }


    public function makeRefund($order_id)
    {

        return $this->where(['user_order_id'=>$order_id,'status'=>1])->update(['status'=>3]);

    }
}